package com.magicode.cms.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.transaction.Transactional;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.magicode.cms.common.assist.json.JsonOperation;
import com.magicode.cms.dao.IVideoDao;
import com.magicode.cms.entiy.base.Article;
import com.magicode.cms.entiy.base.Dictionary;
import com.magicode.cms.entiy.base.News;
import com.magicode.cms.entiy.base.NewsEnterpriseRela;
import com.magicode.cms.entiy.base.Video;
import com.magicode.cms.entiy.base.VideoList;
import com.magicode.cms.service.IVideoService;
import com.magicode.common.dao.ICommonDaoService;
import com.magicode.common.exception.BusinessException;
@Service("servicevideo")
@Transactional
public class VideoServiceImpl extends BaseServiceImpl<Video, IVideoDao> implements IVideoService{
	@Override
	public List<Map<String, Object>> grid(Map<String, String> querywhere) {
		try {
			Integer start = this.getGridStartOrSize(querywhere, 0, field_grid_start);
			Integer size = this.getGridStartOrSize(querywhere, 20, field_grid_size);
			String hql = this.getHql(querywhere);
			hql += " order by t.createTime desc ";
//			hql += " left join "+entity_alias_name+".readOperate as ro ";
//			hql += " left join "+entity_alias_name+".channel as ch ";
//			hql += " left join "+entity_alias_name+".author as au ";
			Map<String,String> gridsel = new HashMap<String,String>();
			gridsel.put(field_id, ""+entity_alias_name+".id as id ");
			gridsel.put(field_title, ""+entity_alias_name+".title as title ");
			gridsel.put("translateTitle", ""+entity_alias_name+".translateTitle as translateTitle ");
//			gridsel.put("shortTitle", ""+entity_alias_name+".shortTitle as shortTitle ");
			gridsel.put("lastUpdateTime", sql_date_method+"("+entity_alias_name+".lastUpdateTime,'"+sql_time_format+"' )  as lastUpdateTime ");
			gridsel.put("subcribeTime", sql_date_method+"("+entity_alias_name+".subcribeTime,'"+sql_time_format+"' )  as subcribeTime ");
			gridsel.put("readOperateTitle", "ro.title as readOperateTitle ");
			gridsel.put("channelTitle", "ch.title as channelTitle ");
			gridsel.put("type", "case when "+entity_alias_name+".type = 1 then '资讯' else '视频' end as type ");
			gridsel.put("author", "au.userName as author ");
			gridsel.put("shareCommentsCount", ""+entity_alias_name+".shareCount || '|' || "+entity_alias_name+".commentsCount "
					+ "  as shareCommentsCount ");
			
			return this.queryMapDataList(hql, gridsel, start, size);
		} catch (Exception e) {
			return new ArrayList<Map<String, Object>>();
		}
		
	}
	@Override
	public String getHql(Map<String, String> map) throws Exception {
		String hql ="from " +Video.class.getName()+" t ";
		hql += " left join "+entity_alias_name+".readOperate as ro ";
		hql += " left join "+entity_alias_name+".channel as ch ";
		hql += " left join "+entity_alias_name+".author as au ";
		if(null!=map && !map.isEmpty()){

			if(null!=map && !map.isEmpty()){
				hql += "where 1 = 1 ";
				if(map.containsKey(field_id)){
					hql = hql+" and "+entity_alias_name+".id = '"+map.get(field_id)+"'";
				}
				if(map.containsKey("title")){
					hql = hql+" and "+entity_alias_name+".title like '%"+map.get("title")+"%'";
				}
				if(map.containsKey("channelId")){
					hql = hql+" and "+entity_alias_name+".channel.id = '"+map.get("channelId")+"'";
				}
				if(map.containsKey("operatelId")){
					hql = hql+" and "+entity_alias_name+".readOperate.id = '"+map.get("operatelId")+"'";
				}
				if(map.containsKey("translateTitle")){
					hql = hql+" and "+entity_alias_name+".translateTitle like '%"+map.get("translateTitle")+"%'";
				}
			}
		}
		return hql;
	}
	public Object getArticle( String id) throws Exception {
		String sql ="from "+News.class.getName() +" t left outer join fetch t.mainPic where t.id='"+id+"'";
		List list = vedioDao.getCommonDaoService().queryList(sql, null);
		if(null!=list && list.size()>0){
			return list.get(0);
		}
		return null;
	}
	
	@Override
	public List<Map<String, Object>> getBeanInfo() {
		List<Map<String, Object>> beaninfo = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(json_key, "title");
		map.put(json_title, "标题");
		map.put("width", 200);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "translateTitle");
		map.put(json_title, "翻译标题");
		map.put("width",200);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "lastUpdateTime");
		map.put(json_title, "更新时间");
		map.put("width", 90);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "subcribeTime");
		map.put(json_title, "发布时间");
		map.put("width", 90);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "readOperateTitle");
		map.put(json_title, "访问权限");
		map.put("width", 50);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "channelTitle");
		map.put(json_title, "所属频道");
		map.put("width", 50);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "type");
		map.put(json_title, "类型");
		map.put("width", 50);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "author");
		map.put(json_title, "作者");
		map.put("width", 50);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "shareCommentsCount");
		map.put(json_title, "分享|评论");
		map.put("width", 70);
		beaninfo.add(map);
		return beaninfo;
	}
	@Override
	public IVideoDao getDao() throws Exception {
		// TODO Auto-generated method stub
		return vedioDao;
	}
	
	@Override
	public List<JsonOperation> getOpts(String url,String id) {
		List<JsonOperation> opts = new ArrayList<JsonOperation> ();
		Video video = null;
		Date createDate = null;
		//用来格式化时间格式，方便在预览的时候请求静态资源
		DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		String dateParam = "";
		try {
			video = super.getObject(id);
			if(null != video){
				createDate = video.getCreateTime();
				dateParam = df.format(createDate);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		JsonOperation opt= new JsonOperation();
		opt.setName("修改");
		opt.setUrl(ctx.getContextPath()+"/"+url+"/getinfo/"+id+"/edit"+url);
		opt.setType("edit");
		opts.add(opt);
		opt= new JsonOperation();
		opt.setName("删除");
		opt.setUrl(ctx.getContextPath()+"/"+url+"/"+id+"?_requestMethod=delete");
		opt.setType("delete2");
		opts.add(opt);
		opt= new JsonOperation();
		opt.setName("预览");
		opt.setUrl(ctx.getContextPath()+"/p/video/sec/"+ dateParam + "/" + id);
		opt.setType("preview");
		opts.add(opt);
		return opts;
	}

	@Autowired
	@Qualifier("daovideo")
	private IVideoDao vedioDao;

	public IVideoDao getVedioDao() {
		return vedioDao;
	}

	public void setVedioDao(IVideoDao vedioDao) {
		this.vedioDao = vedioDao;
	}
	
	@Autowired
	@Qualifier("commonDaoService")
	private ICommonDaoService commonDaoService;
	
	public List getVideoList(){
		String hql = " from com.magicode.cms.entiy.base.VideoList ro ";
		List<VideoList> list = this.commonDaoService.getListByHQL(hql);
		return list;
	}
	
	public Video preview(String id){
		Video video = null;
		try {
			video = (Video) commonDaoService.get(Video.class, id);
			Hibernate.initialize(video.getVideoList());
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return video;
	}
	@Override
	public void setupHead(News news) throws BusinessException {
		// TODO Auto-generated method stub
		String id = news.getId() ;
		if(news.getHead() != null && news.getHead() == 1){ 
			String hql = "select t from " +Video.class.getName()+" t where t.head = 1";
			Map map = new HashMap();
			if(id  != null && id.trim().length() > 0){
				hql += "and t.id != '"+id+"'";
//						map.put("id", id);
				
			}
			List<Object> list = null;
//					if(map.isEmpty()){
				list = this.queryDataList(hql);
//					}
//					else{
//						list = this.queryDataList(hql,map);
//					}
			for(Object otherNews : list){
				if(otherNews instanceof Video){
					((Video)otherNews).setHead(0);
					try {
						this.getDao().editObject((Video) otherNews);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						throw new BusinessException(e);
					}
				}
			}
		}
	}

	@Override
	public List<NewsEnterpriseRela> getNewsEnterpriseRela(String id) {
		List<NewsEnterpriseRela> videoList = new ArrayList();
		Video enterprise = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		String [] fetchJoins = new String[14];
		fetchJoins[0] = "mainPic";
		fetchJoins[1] = "source";
		fetchJoins[2] = "channel";
		fetchJoins[3] = "readOperate";
		fetchJoins[4] = "author";
		fetchJoins[5] = "broadcaster";
		fetchJoins[6] = "compere";
		fetchJoins[7] = "area";
		fetchJoins[8] = "videoList";
		fetchJoins[9] = "videoType";
		fetchJoins[10] = "videoProgram";
		fetchJoins[11] = "enterpriseRelaList";
		fetchJoins[12] = "videoStatus";
		fetchJoins[13] = "videoStyle";	
		try {
			enterprise =super.getObject(id,fetchJoins);
		} catch (Exception e) {
			e.printStackTrace();
		}
		videoList = enterprise.getEnterpriseRelaList();
		return videoList;
	}
	@Autowired
	private ServletContext ctx;

	public ServletContext getCtx() {
		return ctx;
	}
	public void setCtx(ServletContext ctx) {
		this.ctx = ctx;
	}
	@Override
	public List<Dictionary> getvideoTypeList(String id) {
		// TODO Auto-generated method stub
		return null;
	}
}
